package handler

import (
	"ssadmin/common/constant"
	"ssadmin/internal/admin/models"
	"strings"

	log "gitee.com/sansaniot/ssiot-core/logger"
	"gorm.io/gorm"
)

type LoginUser struct {
	Username string `form:"username" json:"username" binding:"required"`
	Password string `form:"password" json:"password" binding:"required"`
	Code     string `form:"code" json:"code"`
	MpAppId  string `form:"mpAppId" json:"mpAppId"`
	Phone    string `form:"phone" json:"phone"`
	Tenant   string `json:"tenant"`
}

func (u *LoginUser) LoginUsername(tx *gorm.DB) (user models.User, err error) {
	err = tx.Table(u.Tenant+".sys_user").Where("username = ?", u.Username).First(&user).Error
	if err != nil {
		log.Errorf("get user error, %s", err.Error())
		return user, err
	}
	return
}

func (u *LoginUser) LoginUserPhone(tx *gorm.DB) (user models.User, err error) {
	err = tx.Table(u.Tenant+".sys_user").Where("mobile = ? ", u.Phone).First(&user).Error
	if err != nil {
		log.Errorf("get user error, %s", err.Error())
		return user, err
	}
	return
}

func (u *LoginUser) GetProfile(db *gorm.DB, user *models.User) error {
	//获取用户分组
	var deptList []models.Dept
	if user.UserId == constant.AdminUser {
		db.Model(&models.Dept{}).Find(&deptList)
	} else {
		var dlist []models.UserDept
		db.Model(&models.UserDept{}).Where("user_id = ?", user.UserId).Find(&dlist)
		ids := []string{}
		for _, deptInfo := range dlist {
			ids = append(ids, deptInfo.DeptId)
		}

		//获取分组名称
		db.Model(&models.Dept{}).Where("id in (?)", ids).Find(&deptList)
	}

	deptIdList := []string{}
	deptNameList := []string{}
	for _, dept := range deptList {
		deptIdList = append(deptIdList, dept.DeptId)
		deptNameList = append(deptNameList, dept.DeptName)
	}
	user.DeptIds = strings.Join(deptIdList, ",")
	user.DeptName = strings.Join(deptNameList, ",")

	//获取用户角色
	var rlist []models.UserRole
	roleIdList := []string{}
	db.Model(&models.UserRole{}).Where("user_id = ?", user.UserId).Find(&rlist)

	for _, ri := range rlist {
		roleIdList = append(roleIdList, ri.RoleId)
	}
	user.RoleId = strings.Join(roleIdList, ",")
	return nil
}
